import { createRouter, createWebHashHistory } from 'vue-router'
import Loading from '@/views/Loading.vue'
import CN from '@/views/CN/CN.vue'
import CN_Index from '@/views/CN/Index.vue'
import CN_List from '@/views/CN/List.vue'
import CN_ReportIndex from '@/views/CN/ReportIndex.vue'
import CN_Detail from '@/views/CN/Detail.vue'
import EN from '@/views/EN/EN.vue'
import EN_Index from '@/views/EN/Index.vue'
import EN_List from '@/views/EN/List.vue'
import EN_ReportIndex from '@/views/EN/ReportIndex.vue'
import EN_Detail from '@/views/EN/Detail.vue'
import { showToast } from 'vant'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'loading',
      component: Loading
    },
    {
      path: '/cn',
      component: CN,
      children: [
        {
          path: '',
          component: CN_Index
        },

        {
          path: 'list',
          component: CN_List,
          meta: {
            requireAuth: true
          }
        },
        {
          path: 'report_index',
          component: CN_ReportIndex,
          meta: {
            requireAuth: true
          }
        },
        {
          path: 'detail',
          component: CN_Detail,
          meta: {
            requireAuth: true
          }
        }
      ]
    },
    {
      path: '/en',
      component: EN,
      children: [
        {
          path: '',
          component: EN_Index
        },
        {
          path: 'list',
          component: EN_List,
          meta: {
            requireAuth: true
          }
        },
        {
          path: 'report_index',
          component: EN_ReportIndex,
          meta: {
            requireAuth: true
          }
        },
        {
          path: 'detail',
          component: EN_Detail,
          meta: {
            requireAuth: true
          }
        }
      ]
    }
  ],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return {
        top: 0
      }
    }
  }
})

router.beforeEach((to, from, next) => {
  // 判断该路由是否需要登录权限
  if (to.meta.requireAuth) {
    // 判断当前的token是否存在
    if (localStorage.token) {
      // console.log("token存在");
      let token_time = localStorage.token_time
      let now_time = parseInt(new Date().getTime() / 1000)
      // console.log(token_time, now_time)

      if (now_time > token_time) {
        // token过期
        localStorage.removeItem('token')
        localStorage.removeItem('token_time')
        showToast('登录已过期，请重新登录')
        next({
          path: '/',
          query: { redirect: to.fullPath }
        })
      } else {
        next()
      }
    } else {
      // console.log("token不存在");
      next({
        path: '/', // 将跳转的路由path作为参数，登录成功后跳转到该路由
        query: { redirect: to.fullPath }
      })
    }
  } else {
    // 如果不需要权限校验，直接进入路由界面
    next()
  }
})

export default router
